package com.lmh.front;

import com.github.pagehelper.util.StringUtil;
import com.lmh.entity.Channel;
import com.lmh.service.ChannelService;
import com.lmh.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/f/channel")
public class FrontChannelController {

    @Autowired
    private ChannelService channelService;

    @GetMapping("/get")
    public Result get(Integer id) {
        if(id == null) {
            return Result.fail("id不能为空");
        }
        Channel detail = channelService.detail(id);
        return Result.ok(detail);
    }

    @GetMapping("/queryByPos")
    public Result getChannelsByPos(String pos) {
        if(StringUtil.isEmpty(pos)) {
            return Result.fail("查询条件不能为空");
        }
        List<Channel> channels = channelService.getChannelsByPos(pos.toUpperCase());
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Channel channel : channels) {
            if(channel.getParentId() == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", channel.getId());
                map.put("name", channel.getName());
                if(channel.getSingle() != null && "Y".equals(channel.getSingle())) {
                    map.put("single", "Y");
                }
                List<Map<String, Object>> children = new ArrayList<>();
                for (Channel entity : channels) {
                    if(entity.getParentId().equals(channel.getId())) {
                        Map<String, Object> subMap = new HashMap<>();
                        subMap.put("id", entity.getId());
                        subMap.put("name", entity.getName());
                        subMap.put("single", entity.getSingle());
                        children.add(subMap);
                    }
                }
                if(children.size() > 0) {
                    map.put("children", children);
                }
                mapList.add(map);
            }
        }
        return Result.ok(mapList);
    }
}
